package com.campsys.util;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.campsys.domain.param.StudentAddExcel;
import com.campsys.service.IStudentService;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class StudentBatchAddListener implements ReadListener<StudentAddExcel> {
    /**
     * 每次读取的最多行数
     */
    private static final int MAX_ROW_PER_READ = 5 ;
    /**
     * 利用studentDao将读取到的数据，批量存入数据库。
     */
    private IStudentService studentService ;
    /**
     * 存储读取到的数据
     */
    private List<StudentAddExcel> cachedReadData = ListUtils.newArrayListWithExpectedSize(MAX_ROW_PER_READ) ;
    public StudentBatchAddListener(IStudentService studentService) {
        this.studentService = studentService ;
    }
    /**
     * 每次easyexcel读取到一行数据，都会调用该方法
     * @param studentAddExcel
     * @param analysisContext
     */

    @Override
    public void invoke(StudentAddExcel studentAddExcel, AnalysisContext analysisContext) {
        log.info("读取到一条学生信息：{}", studentAddExcel) ;
        cachedReadData.add(studentAddExcel) ;
        if (cachedReadData.size() >= MAX_ROW_PER_READ) {

            // 达到每行最大读取数，需要将数据写入数据库
            log.info("数据写入数据库：{}", cachedReadData);
            studentService.addStudentBatch(cachedReadData);
            // 清空缓存数据
            cachedReadData = ListUtils.newArrayListWithExpectedSize(MAX_ROW_PER_READ) ;

        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 所有数据读取完毕，需要将剩余的数据写入数据库
        log.info("数据写入数据库：{}", cachedReadData) ;
        studentService.addStudentBatch(cachedReadData);
        log.info("读取完毕");
    }
}
